from django.db import models
from datetime import datetime

from pypsqueak.versioning.fields import PickledObjectField
from django.contrib.auth.models import User

#  Try to load the faster cPickle library
try:
	import cPickle as pickle
except ImportError:
	import pickle


class Version(models.Model):
	""" Stores versions """
	model_name = models.CharField(max_length=255, default="")
	model_pk = models.IntegerField()
	pickle_field = PickledObjectField()
	user = models.ForeignKey(User, editable=False)
	created = models.DateTimeField( default=datetime.now, editable=False )
	draft = models.BooleanField(default=False,editable=False)

	def __unicode__(self):
		return "Pickled " + self.pickle_field.__class__.__name__ + "." + str(self.model_pk)

	def __init__(self, *args, **kwargs):
		super(Version, self).__init__(*args, **kwargs)

	def setObject(self, SaveObject):
		self.pickle_field = SaveObject
		self.model_name = SaveObject.__class__.__name__
		self.model_pk = SaveObject.pk

	def getObject(self):
		return self.pickle_field


	class Admin:
		pass


	class Meta:
		get_latest_by = "created"
		ordering = [ "model_name", "model_pk",'created' ]


class VersionedModel(models.Model):
	""" Provides automatic versioning for inheriting objects """

	def save(self, force_insert=False, force_update=False):
		"""Save a new version each time the master page is saved."""
		super(VersionedModel, self).save(force_insert,force_update)
		v=Version()
		v.setObject(self)
		v.user = self.user
		v.save()

	def getVersions(self):
		if self.pk:
			return Version.objects.filter(
				model_name=self.__class__.__name__,
				model_pk=self.pk)
		else:
			return {}

	#def getDraft(self):
		""" Find any draft versions """
	#	return Version.objects.filter(
	#			model_name=self.__class__.__name__,
	#			model_pk=self.pk,
	#			draft=True)
	#d#ef setDraft(self):
	#	v=Version()
	#	v.setObject(self)
	#	v.draft = True
	#	v.save()

class VersionedModel_Test(VersionedModel):
	""" A test object to test versioning form """
	title = models.CharField(max_length=255, default="Title")
